package com.atguigu.ucenterService.controller;

import com.atguigu.commonUtils.JwtUtils;
import com.atguigu.ucenterService.entity.UcenterMember;
import com.atguigu.ucenterService.service.UcenterMemberService;
import com.atguigu.ucenterService.utils.ConstantWxUtils;
import com.atguigu.ucenterService.utils.HttpClientUtils;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.HashMap;

@Api(tags = "微信扫码登录")
@Controller
@CrossOrigin
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Resource
    private UcenterMemberService ucenterMemberService;

    @ApiOperation("生成微信二维码")
    @GetMapping("/login")
    public String getWxCode(){

        // 微信开放平台授权baseUrl
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        String redirectUrl = ConstantWxUtils.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (Exception e) {
            throw new RuntimeException();
        }

        String url = String.format(baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUrl,
                "atguigu");
        return "redirect:"+url;
    }

    @GetMapping("/callback")
    public String callback(String code, String state) {
        try {
            //获取code值，临时票据，类似于验证码
            //拿着code请求微信固定地址，得到两个值access_token和openId
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantWxUtils.WX_OPEN_APP_ID,
                    ConstantWxUtils.WX_OPEN_APP_SECRET,
                    code);
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl); //里面包含access_token和openId
            Gson gson = new Gson();
            HashMap map = gson.fromJson(accessTokenInfo, HashMap.class);
            String access_token = (String)map.get("access_token");
            String openid = (String)map.get("openid");

            //判断数据库是否存在相同的微信信息，如果不存在则添加。根据openid判断
            UcenterMember member = ucenterMemberService.getUserByOpenId(openid);
            if (member == null) {
                //拿着access_token和openId再去请求一个固定地址，获取扫码人的信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String userInfo = HttpClientUtils.get(userInfoUrl);
                //获取返回的用户信息
                HashMap userMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userMap.get("nickname");
                String headimgurl = (String) userMap.get("headimgurl");

                member = new UcenterMember();
                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(headimgurl);
                ucenterMemberService.save(member);
            }
            //使用jwt根据member对象生成token字符串
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());
            return "redirect:http://localhost:3000?token="+token;
        }catch (Exception e){
            throw new RuntimeException();
        }
    }




}
